package aidturith.db.hibernate;

import java.net.URL;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import aidturith.ihm.MainFrame;

/**
 * Wrapper pour démarrer Hibernate dans un bloc statique d'initialisation.
 * @author Scub-Foundation
 */
public class HibernateUtil {

	private static SessionFactory sessionFactory;
	private static ServiceRegistry serviceRegistry;
	private static URL path;

	static {
		try {
			// eclipse
			path = MainFrame.class.getResource("../../hibernate_standalone.cfg.xml");

			// jar
			//path = MainFrame.class.getResource("/hibernate_standalone.cfg.xml");

			Configuration configuration = new Configuration();
			configuration.configure(path);
			serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Accesseur.
	 * @return la session existante
	 * @throws HibernateException
	 */
	public static Session getSession() throws HibernateException {
		return sessionFactory.openSession();
	}

	/**
	 * Ferme la session Hibernate.
	 * @throws HibernateException
	 */
	public static void closeSession() throws HibernateException {
		sessionFactory.close();
	}

}
